package com.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;

import org.jdom.JDOMException;

import constants.ProjectConstants;

class InitServer extends Thread {

	private Socket conexao;
	private int socketNumber;
	private Socket clientSocket;
	private DataInputStream in;
	private DataOutputStream out;

	public static void main(String args[]) {
		int numero = 0;
		Time time = new Time();
		
		try {
			ServerSocket listenSocket = new ServerSocket(ProjectConstants.serverPort);
			System.out.println("À Escuta no Porto "+ ProjectConstants.serverPort);
			
			while (true) {
				Socket clientSocket = listenSocket.accept();
				numero++;
				InitServer c = new InitServer(clientSocket, clientSocket.getPort());
				
			}
		} catch (IOException e) {
			System.out.println("Listen:" + e.getMessage());
		}
	}

	public InitServer(Socket aClientSocket, int numero) {
		socketNumber = numero;
		try {
			clientSocket = aClientSocket;
			in = new DataInputStream(clientSocket.getInputStream());
			out = new DataOutputStream(clientSocket.getOutputStream());
			this.start();
		} catch (IOException e) {
			System.out.println("Connection:" + e.getMessage());
		}
	}

	public void run() {
		try {
			while (true) {
				// an echo server
				String xmlRequest = in.readUTF();
				System.out.println("Socket " + socketNumber + " - Recebeu: " + xmlRequest);
				String xmlReply = new ServerParser().parser(xmlRequest);
				out.writeUTF(xmlReply);
			}
		} catch (EOFException e) {
			System.out.println("EOF:" + e);
		} catch (IOException e) {
			System.out.println("IO:" + e);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		}
	}
}
